// pages/waitmassage/waitmassage.js
const adapters = require("../../utils/adapters");
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
Page({
 
  data: {
    header: {
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight
    },
    optionList: [
      {
        title:"待发货",
        mode: 0,
      },
      {
        title:"待回复",
        mode: 1,
      },
      {
        title:"已回复",
        mode: 2,
      }
    ],
    pageMode: null,
    operateMode: 1,
    activeItem: null,
    search: {
      value: ''
    },
    allUnDealMaintenanceList: [],
    userInfo: null,
  },
  changeOperateMode() {
    let operateMode = this.data.operateMode
    let allUnDealMaintenanceList = this.data.allUnDealMaintenanceList
    if(operateMode === 0) {
      operateMode = 1
    } else {
      operateMode = 0
    }
    allUnDealMaintenanceList.forEach(item => item.checkStatus = false);
    this.setData({
      allUnDealMaintenanceList: allUnDealMaintenanceList,
      operateMode: operateMode,
      activeItem: null,
    });
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },
 
  onLoad(options) {
    const pageMode = Number(options.pageMode)
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      pageMode: pageMode,
    })
    this.loadPage();
  },

  searchBarOnChange(e) {
    this.setData({
      'search.value': e.detail,
    });
  },
  
  searchBarOnSearch() {
    const text = this.data.search.value; // 获取搜索框的值
    const allUnDealMaintenanceList = this.data.allUnDealMaintenanceList;
  
    // 遍历数组并根据条件设置 hidden 属性
    allUnDealMaintenanceList.forEach(item => {
      if (text === '') {
        // 如果搜索框为空，显示所有项
        item.hidden = false;
      } else {
        // 如果 batteryUnite 存在且包含搜索文本，则显示该项
        if (item.batteryUnite && item.batteryUnite.includes(text)) {
          item.hidden = false;
        } else {
          item.hidden = true;
        }
      }
    });
  
    // 更新数据到页面
    this.setData({
      allUnDealMaintenanceList: allUnDealMaintenanceList
    });
  
    console.log(allUnDealMaintenanceList); // 打印结果以验证
  },

  goDetail(e) {
    console.log(e)
    wx.navigateTo({
      url: `/pages/detail/detail?pagemode=${e.currentTarget.dataset.pagemode}&maintenancenumber=${e.currentTarget.dataset.maintenancenumber}`,
    });
  },

  goEdit(e) {
    wx.navigateTo({
      url: `/pages/index/index?pagemode=1&maintenancenumber=${e.currentTarget.dataset.maintenancenumber}`,
    });
  },

  tapItem(e) {
    let index = e.currentTarget.dataset.index;
    if(this.data.operateMode === 0) {
      let list = this.data.allUnDealMaintenanceList
      var checkStatus = list[index].checkStatus
      if ( checkStatus === 'allTrue') {
        list = list.map(item => ({
          ...item,
          checkStatus: true
        }));
      }
      list[index].checkStatus = !checkStatus
      if (!list.some(item => !item.checkStatus)) {
        list = list.map(item => ({
          ...item,
          checkStatus: 'allTrue'
        }));
      }
      this.setData({
        allUnDealMaintenanceList: list
      })
    } else {
      if ( this.data.activeItem === index) {
        index = null
      }
      this.setData({
        activeItem: index
      })
    }
  },

  checkAll() {
    let list = this.data.allUnDealMaintenanceList;
    const hasUnchecked = list.some(item => !item.checkStatus);
    if (hasUnchecked) {
      list = list.map(item => ({
        ...item,
        checkStatus: 'allTrue'
      }));
    } else {
      list = list.map(item => ({
        ...item,
        checkStatus: false
      }));
    }
    this.setData({
      allUnDealMaintenanceList: list
    });
  },

  async operateMaintenanceListStatus(e) {
    // 从页面变量中获取全部被选中的工单和用户信息
    const { allUnDealMaintenanceList, userInfo } = this.data;
    // 获取用户点击的按钮类型，如果点击了删除工单按钮则此处type会被赋值为1
    let type = Number(e.currentTarget.dataset.type);
    try {
      // 显示确认弹窗让用户确认是否继续操作
      await Dialog.confirm({
        title: '确认进行此操作',
        message: `${type === 1 ? '删除' : '发货'} `,
      });
      
      // 调用接口去更新状态
      const res = await adapters.setMaintenanceListStatus({
        type: type, // 带上type告诉接口这是发货还是取消
        allUnDealMaintenanceList: allUnDealMaintenanceList,  // 这个变量是所有需要操作的工单
        phoneNumber: userInfo.phoneNumber  // 发送用户的手机号
      });
  
      if (res.success) {
        wx.showToast({ title: res.message, icon: 'none' });
        this.loadPage(); // 刷新页面数据
      } else {
        wx.showToast({ title: res.message, icon: 'none' });
      }
    } catch (err) {
      // 用户取消或网络异常等
      if (err.closeAction === 'cancel') {
        console.log('用户取消操作');
        wx.showToast({
          title: '取消了该操作',
          icon: 'none'
        })
      } else {
        console.error('操作失败:', err);
        wx.showToast({ title: '操作失败:' + err, icon: 'none' });
      }
    }
  },

  async loadPage() {
    // 从页面变量中获取用户信息和页面的模式（待发货/待回复/已处理）
    const {userInfo, pageMode} = this.data;

    try {
      // 将页面的模式和用户手机号发送给接口获取工单列表
      const res = await adapters.getMaintenanceList({ type: pageMode, phoneNumber: userInfo.phoneNumber });

      this.setData({
        allUnDealMaintenanceList: res.data || []  // 将工单列表内容更新到页面上
      })
  
    } catch (err) {
      console.error('获取维修列表失败:', err);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  }
})